package com.oeandn.system.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.oeandn.common.model.PageModel;
import com.oeandn.common.utils.TreeUtil;
import com.oeandn.db.base.service.BaseService;
import com.oeandn.system.mapper.InspectPointMapper;
import com.oeandn.system.model.Dept;
import com.oeandn.system.model.InspectPoint;
import com.oeandn.system.model.InspectPointItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;

/**
 * <p>
 * 巡检点 服务实现类
 * </p>
 *
 * @author 饮水机管理员
 * @since 2022-08-09
 */
@Slf4j
@Service
public class InspectPointService extends BaseService<InspectPointMapper, InspectPoint> {


    @Resource
    InspectPointItemService inspectPointItemService;


    @Resource
    InspectPathService inspectPathService;

    @Resource
    ApproveRecordService approveRecordService;


    /**
     * 获取表格数据
     *
     * @param inspectPoint
     * @param pageModel
     * @return
     */
    public IPage<InspectPoint> pageListByEntity(InspectPoint inspectPoint, PageModel pageModel) {
        LambdaQueryWrapper<InspectPoint> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(StrUtil.isNotBlank(inspectPoint.getInspectPointType()), InspectPoint::getInspectPointType,
                inspectPoint.getInspectPointType());
        queryWrapper.like(StrUtil.isNotBlank(inspectPoint.getInspectPointName()), InspectPoint::getInspectPointName,
                inspectPoint.getInspectPointName());
        queryWrapper.like(StrUtil.isNotBlank(inspectPoint.getSubordinateUnits()), InspectPoint::getSubordinateUnits,
                inspectPoint.getSubordinateUnits());
        queryWrapper.like(StrUtil.isNotBlank(inspectPoint.getDeviceName()), InspectPoint::getDeviceName,
                inspectPoint.getDeviceName());
        queryWrapper.like(StrUtil.isNotBlank(inspectPoint.getDeviceType()), InspectPoint::getDeviceType,
                inspectPoint.getDeviceType());
        queryWrapper.like(StrUtil.isNotBlank(inspectPoint.getDeviceTakeChargeName()),
                InspectPoint::getDeviceTakeChargeName, inspectPoint.getDeviceTakeChargeName());
        queryWrapper.like(StrUtil.isNotBlank(inspectPoint.getDeviceLebelId()), InspectPoint::getDeviceLebelId,
                inspectPoint.getDeviceLebelId());
        queryWrapper.like(StrUtil.isNotBlank(inspectPoint.getDeviceLebelName()), InspectPoint::getDeviceLebelName,
                inspectPoint.getDeviceLebelName());
        queryWrapper.like(StrUtil.isNotBlank(inspectPoint.getDeviceStatus()), InspectPoint::getDeviceStatus,
                inspectPoint.getDeviceStatus());
        queryWrapper.like(StrUtil.isNotBlank(inspectPoint.getAccessory()), InspectPoint::getAccessory,
                inspectPoint.getAccessory());
        queryWrapper.like(StrUtil.isNotBlank(inspectPoint.getCoord()), InspectPoint::getCoord, inspectPoint.getCoord());
        queryWrapper.like(StrUtil.isNotBlank(inspectPoint.getIcon()), InspectPoint::getIcon, inspectPoint.getIcon());
        queryWrapper.like(StrUtil.isNotBlank(inspectPoint.getHistoryCode()), InspectPoint::getHistoryCode,
                inspectPoint.getHistoryCode());
        return super.page(pageModel, queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean saveInspectPoint(InspectPoint inspectPoint) {
        inspectPoint.setDelFlag("2");
        //int insert = this.baseMapper.insert(inspectPoint);
        boolean save = this.save(inspectPoint);
        //判断是否需要审批
        // if (0 < insert) {
        if (save) {
            //需要审批
            Long id = inspectPoint.getId();
            //  调用审批
            return approveRecordService.saveApproveRecord(inspectPoint.getDeptId(),id,"2","0");
        }
        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean updateInspectPoint(InspectPoint inspectPoint) {
        //添加新数据
        InspectPoint point = new InspectPoint();

        point.setParentId(inspectPoint.getParentId());
        point.setInspectPointType(inspectPoint.getInspectPointType());
        point.setInspectPointName(inspectPoint.getInspectPointName());
        point.setSubordinateUnits(inspectPoint.getHistoryCode());
        point.setDeviceName(inspectPoint.getDeviceName());
        point.setDeviceType(inspectPoint.getDeviceType());
        point.setDeviceTakeChargeBy(inspectPoint.getDeviceTakeChargeBy());
        point.setDeviceTakeChargeName(inspectPoint.getDeviceTakeChargeName());
        point.setDeviceLebelId(inspectPoint.getDeviceLebelId());
        point.setDeviceLebelName(inspectPoint.getDeviceLebelName());
        point.setDeviceStatus(inspectPoint.getDeviceStatus());
        point.setAccessory(inspectPoint.getHistoryCode());
        point.setCoord(inspectPoint.getCoord());
        point.setIcon(inspectPoint.getIcon());
        point.setDelFlag("2");
        //设置旧的id
        point.setHistoryId(inspectPoint.getId());
        boolean save = this.save(point);

        //发送审批
        if (save) {
            //需要审批
            Long id = point.getId();
            //TODO 调用审批
            //log.info("巡检点修改成功返回传送审批id = " + id);
            return approveRecordService.saveApproveRecord(inspectPoint.getDeptId(),id,"2","0");
        }
        return false;
    }


    /**
     * 功能描述: 功能描述: 审批通过调用 修改数据
     *
     * @param id 业务主键id
     * @return null
     * @author GGW
     * @date 2022-08-10
     */
    @Transactional(rollbackFor = Exception.class)
    public void upd(Long id) {

        InspectPoint point = this.getById(id);


        //修改原来的数据为 历史
        InspectPoint updpoint = new InspectPoint();
        updpoint.setId(point.getHistoryId());
        updpoint.setHistoryId(point.getId());
        updpoint.setHistoryCode("1");
        this.updateById(updpoint);

        //修改原来关联的历史
        List<InspectPoint> list = this.list(new QueryWrapper<InspectPoint>().eq("history_code", 1).eq("history_id",
                point.getHistoryId()));
        //log.info("巡检点添加成功返回添加id = " + JSON.toJSONString(list));

        if (list.size() > 0) {
            list.forEach(item -> {
                item.setHistoryCode("1");
                item.setHistoryId(point.getId());
            });
        }
        this.updateBatchById(list);
        //修改原来的关联这个的父类 id为现在的id
        List<InspectPoint> list1 = this.list(new QueryWrapper<InspectPoint>().eq("parent_id",
                point.getHistoryId()));
        // log.info("巡检点修改所有父类 " + JSON.toJSONString(list1));
        if (list1.size() > 0) {
            list1.forEach(item -> {
                item.setParentId(point.getId());
            });
        }
        this.updateBatchById(list1);

        // 修改巡检项关联的数据
        List<InspectPointItem> pointItems = inspectPointItemService.list(
                new QueryWrapper<InspectPointItem>().eq("inspect_point_id", point.getHistoryId())
        );
        if (0 < pointItems.size()) {
            pointItems.forEach(item -> {

                item.setInspectPointId(point.getId());
            });
        }

        inspectPointItemService.updateBatchById(pointItems);

        // 修改路线关联的数据
        //inspectPathService.updateInspectPathPoint(point.getHistoryId(), point.getId());


        point.setHistoryId(0L);
        point.setDelFlag("0");
        updateById(point);
    }

    public List<InspectPoint> getPointTreeList() {
        List<InspectPoint> listPoint = list();
        return TreeUtil.listToTree(listPoint);
    }
}
